package org.jeecgframework.web.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyRoomServiceI;
import org.jeecgframework.web.system.pojo.base.ZyRoomEntity;
import org.jeecgframework.web.system.pojo.base.ZyRoomHisEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 影厅
 * @author ZhangYunlong
 * @date 2016-04-01 10:47:16
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyRoomController")
public class ZyRoomController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyRoomController.class);

	@Autowired
	private ZyRoomServiceI zyRoomService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService zyCommonService;
	
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 影厅列表 页面跳转
	 */
	@RequestMapping(params = "zyRoom")
	public ModelAndView zyRoom(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_room/zyRoomList");
	}
	
	/**
	 * @author xiul
	 * 2016-7-1 下午2:52:12
	 * Description 影厅列表页 datagrid 
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(ZyRoomEntity zyRoom,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyRoomEntity.class, dataGrid);
		cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"),Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
        // Add start 没有检索条件时不检索内容 Amy 2018/3/9
		boolean flag = false;
		Map<String, String[]> parameterMap = request.getParameterMap();
		for (String key : parameterMap.keySet()) {
			if(key.equals("roomCinema.name") || key.equals("roomNum")){
				if(!StringUtil.isEmpty(parameterMap.get(key)[0])){
					flag = true;//页面 查询条件为空不做查询
					break;
				}
			}
		}
        // Add End 没有检索条件时不检索内容 Amy 2018/3/9
		if(flag){
			//查询条件组装器
			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyRoom, request.getParameterMap());
			try{
			//自定义追加查询条件
			}catch (Exception e) {
				throw new BusinessException(e.getMessage());
			}
			cq.add();
			this.zyRoomService.getDataGridReturn(cq, true);
		}else{
			dataGrid.setResults(new ArrayList<>());
		}
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * @author xiul
	 * @date 2016-4-26 上午11:30:05
	 * @Description 选择所属影厅页 
	 */
	@RequestMapping(params="zyChooseRoomForEquipment")
	public ModelAndView zyChooseRoomForEquipment(HttpServletRequest request){
		String belongCinemaId = oConvertUtils.getString(request.getParameter("belongCinemaId"));
		request.setAttribute("params", "belongCinemaId="+belongCinemaId);
		return new ModelAndView("com/zybk/zy_room/zyChooseRoomForEquipment");
	}
	
	/**
	 * @author xiul
	 * 2016-4-26 上午11:30:48
	 * Description 设备添加 更新页 选择所属影厅页  datagrid
	 */
	@RequestMapping(params = "zyChooseRoomForEquipmentDataGrid")
	public void zyChooseRoomForEquipmentDataGrid(ZyRoomEntity zyRoom,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		String belongCinemaId = oConvertUtils.getString(request.getParameter("belongCinemaId"));
		List<Map<String, Object>> results = zyRoomService.queryDatagridResultForChooseRoomEquipment(request,belongCinemaId);
		dataGrid.setResults(results);
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * @Description 逻辑删除影厅
	 * @author ZhangYunlong
	 * @Date 2016-3-31 下午4:53:06
	 */
	@RequestMapping(params = "dologicDel")
	@ResponseBody
	public AjaxJson dologicDel(ZyRoomEntity zyRoom, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		zyRoom = systemService.getEntity(ZyRoomEntity.class, zyRoom.getId());
		message = "影厅[" + zyRoom.getRoomNum() + "]删除成功";
		try{
			zyRoom.setIsDelete("1");
			zyRoomService.saveOrUpdate(zyRoom);
			ZyRoomHisEntity zyRoomHis = new ZyRoomHisEntity();
			MyBeanUtils.copyBeanNotNull2Bean(zyRoom, zyRoomHis);
			zyRoomHis.setBusId(zyRoom.getId());
			zyRoomHis.setDataStatus("delete");
			zyRoomService.save(zyRoomHis);
		}catch(Exception e){
			e.printStackTrace();
			message = "影厅[" + zyRoom.getRoomNum() + "]删除失败";
		}
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 添加影厅
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyRoomEntity zyRoom, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "影厅[" + zyRoom.getRoomNum() + "]添加成功";
		try{
			if(zyRoom.getRoomCinema().getId().equals("")){
				zyRoom.setRoomCinema(null);
			}
			zyRoom.setIsDelete("0");
			zyRoomService.save(zyRoom);
			ZyRoomHisEntity zyRoomHis = new ZyRoomHisEntity();
			MyBeanUtils.copyBeanNotNull2Bean(zyRoom, zyRoomHis);
			zyRoomHis.setId(null);
			zyRoomHis.setBusId(zyRoom.getId());
			zyRoomHis.setDataStatus("create");
			zyRoomService.save(zyRoomHis);
		}catch(Exception e){
			e.printStackTrace();
			message =  "影厅[" + zyRoom.getRoomNum() + "]添加失败";
		}
		systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新影厅
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ZyRoomEntity zyRoom, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		ZyRoomEntity t = zyRoomService.get(ZyRoomEntity.class, zyRoom.getId());
		String name = t.getRoomNum();
		message = "影厅[" + name + "]更新成功";
		try {
			MyBeanUtils.copyBeanNotNull2Bean(zyRoom, t);
			zyRoomService.saveOrUpdate(t);
			ZyRoomHisEntity zyRoomHis = new ZyRoomHisEntity();
			MyBeanUtils.copyBeanNotNull2Bean(t, zyRoomHis);
			zyRoomHis.setBusId(t.getId());
			zyRoomHis.setDataStatus("update");
			zyRoomService.save(zyRoomHis);
		} catch (Exception e) {
			e.printStackTrace();
			message = "影厅[" + name + "]更新失败";
		}
		systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 影厅新增页面跳转
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ZyRoomEntity zyRoom, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyRoom.getId())) {
			zyRoom = zyRoomService.getEntity(ZyRoomEntity.class, zyRoom.getId());
			req.setAttribute("zyRoomPage", zyRoom);
		}
		return new ModelAndView("com/zybk/zy_room/zyRoom-add");
	}
	/**
	 * 影厅编辑页面跳转
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ZyRoomEntity zyRoom, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyRoom.getId())) {
			zyRoom = zyRoomService.getEntity(ZyRoomEntity.class, zyRoom.getId());
			req.setAttribute("zyRoomPage", zyRoom);
		}
		return new ModelAndView("com/zybk/zy_room/zyRoom-update");
	}
	
	/**
	 * 影厅查看页面跳转
	 */
	@RequestMapping(params = "goView")
	public ModelAndView goView(ZyRoomEntity zyRoom, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyRoom.getId())) {
			zyRoom = zyRoomService.getEntity(ZyRoomEntity.class, zyRoom.getId());
			req.setAttribute("zyRoomPage", zyRoom);
		}
		return new ModelAndView("com/zybk/zy_room/zyRoom-view");
	}
	
	/**
	 * @author xiul
	 * 2016-6-16 下午3:30:22
	 * Description 检查同一影院下影厅号的唯一性 
	 * @param param validataForm ajaxUrl 参数
	 */
	@ResponseBody
	@RequestMapping(params="checkRoomNumUnique")
	public ValidForm checkRoomNumUnique(@RequestParam(value="param",defaultValue="")String param,
			@RequestParam(value="roomId",defaultValue="")String roomId,
			@RequestParam(value="cinemaId",defaultValue="")String cinemaId){
		ValidForm vf = new ValidForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total ");
		sql.append(" FROM zy_room rm");
		sql.append(" WHERE ");
		sql.append(" rm.room_cinema = '"+cinemaId+"' ");
		sql.append(" AND rm.room_num = '"+param+"' ");
		sql.append(" AND rm.is_delete = 0 ");
		if(StringUtil.isNotEmpty(roomId)){
			sql.append(" AND id != '"+roomId+"' ");
		}
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			vf.setStatus(ValidForm.N);
			vf.setInfo("当前影院下影厅号已存在");
		}
		return vf;
	}
	
}
